package aurora

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"strings"
)

const (
	goDriver = "go"
)

func (a *Aurora) loadDatabase() {
	if a.config == nil {
		//如果配置文件没有加载成功，将不做任何事情
		return
	}
	dbinfo := a.config.GetStringMapString("aurora.database")
	//开始检验参数个数
	if len(dbinfo) != 5 {
		return
	}
	a.Info("load DB configuration information")
	a.loadSqlDB(dbinfo["user"], dbinfo["password"], dbinfo["host"], dbinfo["db"], dbinfo["driver"])
}

// loadORM 加载 ORM 框架
func (a *Aurora) loadSqlDB(user, password, host, db, driver string) {
	if user == "" || host == "" || db == "" || driver == "" {
		return
	}
	dns := fmt.Sprintf("%s:%s@(%s)/%s", user, password, host, db)
	//解析 driver 按照 . 进行切割得到 具体 orm 数据库类型
	drivers := strings.Split(driver, ".")
	//driver 需要解析出2个值
	if len(drivers) != 2 {
		return
	}
	switch drivers[0] {

	case goDriver:
		DB, err := sql.Open(drivers[1], dns)
		if err != nil {
			a.Panic(err.Error())
			return
		}
		a.component.put(driver, DB)
	}
}
